# -*- encoding:utf8 -*-
import json
from django.utils import timezone
from datetime import datetime, date, time, timedelta
from attendance.tool_func import get_or_none
from attendance.models import LeaveApplication,LeaveModel
from attendance.convert import str2dt,dt2str
from staff.models import StaffInfo
# from django.db import transaction
from leave_match import match
import re
from ..timeblock import divide_timeblock,timeblock_span
from attendance.leave.annual import annual_left
from attendance.leave.swap_off import swapoff_left


def submit_leave(staff, category, start_time, end_time, reason):
    """提交上来的请假
    
    Args:
    @type staff: SubmittedLeave
    @category:种类，'annual','swap_off','sick'...
    @start_time: 浏览器传过来的时间字符串
    @end_time:
    @reason:请假原因
    
    Return:
    {'status':''}
    """
    span=timeblock_span(divide_timeblock(start_time, end_time,staff.workshift))
    if category=='annual_leave':
        al=annual_left(staff)
        total=al +4*60  # 可以透支  0.5 天
        if total<span:
            raise UserWarning, {'status':'fail','msg':'annual left:%.2f overdraw:0.5 day =%.2f,but your application is %.2f'%(al/(8.0*60),total/(8.0*60),span/(8.0*60))}
    elif category=='swap_off':
        swap_left=swapoff_left(staff)
        if swapoff_left<span:
            raise UserWarning, {'status':'fail','msg':'swap off:%.2f,but your application is %.2f'%(swap_left/(8.0*60),span/(8.0*60))}
    
    leave = LeaveApplication(staff=staff, category=category, start_time=start_time, end_time=end_time,
                               reason=reason, create_by=staff.employee_id, status='pending')
    leave.save()
        #pump_chain(leave)
    return leave
  
def post_application(app_leave):
    """
    将假期分割成连续的时间段，并且投递到UsedLeave
    
    Args:
    @leave: SubmittedLeave数据表的对象
    
    """
    # leave = SubmittedLeave.objects.get(id=leaveid)
    ls = divide_timeblock(str2dt(app_leave.start_time),str2dt(app_leave.end_time))

    # 删除 晚一些的 假期匹配关系 (因为匹配应该按照请假顺序匹配)
    for later_leave in LeaveModel.objects.filter(staff=app_leave.staff, start_time__gt=app_leave.start_time,
                                                category=app_leave.category):
        later_leave.relation.all().delete()
        later_leave.matched = False
        later_leave.save()

    for l in ls:
        LeaveModel(staff=app_leave.staff, category=app_leave.category, start_time=l['start_time'],
                  end_time=l['end_time'], submited_leave=app_leave).save()

        # ---------匹配(所有未匹配的)可用假期与申请的假期（年假与调休）------------------
    match(app_leave.staff)




